<template>
  <view :class="{'is-active': isActive}" class="p-product">
    <view class="_carousel">
      <view class="_picture">
        <p-swiper
          ref="swiperRef"
          :list="detail.mainPic"
          :dot-placement="isActive ? 'top-right' : 'bottom'"
          :mode="isActive ? 'aspectFit' : 'aspectFill'"
          height="1000rpx"
          is-radius
        />
      </view>
      <view v-if="isShowProduct" class="_product">
        <view class="_animation">
          <view class="_header">
            <view v-if="detail.labelName || detail.productShortName" class="_abbreviation">
              <view v-if="detail.labelName" class="_tag">{{ detail.labelName }}</view>
              <view v-if="detail.productShortName" class="_name">{{ detail.productShortName }}</view>
            </view>
          </view>
          <view class="_card">
            <x-send-coupon v-if="couponSendList && !isAlreadyReceive" :coupon="couponSendList" @sendcoupon="handleCardSendCoupon">
              <view class="coupon-holder"></view>
            </x-send-coupon>
            <view @click="handleToDetail">
              <view class="_price">
                <view v-if="coupon" class="_new_name">券后</view>
                <view class="_new_price" :data-value="payPrice.suffix">{{ payPrice.prefix }}</view>
              </view>
              <view class="_title">
                <text v-if="detail.labelName" class="_tag">{{ detail.labelName }}</text>
                <text class="_name">{{ detail.productTitle }}</text>
                <text class="_more">详情</text>
                <x-icon name="icon-017" size="36" color="#EB441F" />
              </view>
              <!-- 服务 -->
              <view v-if="isServicePromise && safeguardList && safeguardList.length" class="_server">
                <p-server
                  :title="false"
                  :serveList="safeguardList"
                  content-style="padding: 0; border: 0"
                  @showServiceDrawer="serviceVisible = true"
                />
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="_tools">
      <x-send-coupon v-if="couponSendList && !isAlreadyReceive" :coupon="couponSendList" @sendcoupon="handleSendCoupon">
        <view class="_button">领券购买</view>
      </x-send-coupon>
      <view v-else class="_button" @click="handleShowSku">立即购买</view>
    </view>
  </view>
</template>

<script>
import XSendCoupon from '@/components/x-send-coupon';
import XIcon from '@/components/x-icon';
import PSwiper from '@/pages/advertising/components/p-swiper';
import PServer from '@/pages/goods-detail/components/p-server';
import { mapState } from 'vuex';

export default {
  name: 'PProduct',
  components: {
    XIcon,
    XSendCoupon,
    PServer,
    PSwiper
  },
  props: {
    isActive: {
      type: Boolean,
      default: false
    },
    detail: {
      type: Object,
      default: () => {}
    },
    index: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      current: 0,
      isShowProduct: false,
      isAlreadyReceive: false
    };
  },
  computed: {
    ...mapState({
      // 页面价格
      pagePrice: state => state['product'].pageDetail?.pagePrice,
      // 价格模块
      priceModule: state => state['product'].pageModule?.price,
      // 服务模块
      isServicePromise: state => state['product'].pageModule?.servicePromise,
      // 服务承诺
      safeguardList: state => state['product'].safeguardList,
      // 当前商品关联的可领取优惠券，只支持批次领取，最多10个
      couponSendList: state => state['product'].couponSend,
      // 商品可用优惠券
      couponList: state => state['product'].couponList,
      // 规格模式：1-统一规格；2-多规格；3-套餐模式
      skuMode: state => state['product'].productDetail?.skuMode
    }),
    // 大促金额
    promotionDiscountAmount() {
      return this.priceModule && this.priceModule.value === 2 ? this.priceModule.discountAmount : 0;
    },
    // 待领取的优惠券
    couponVoList() {
      return this.couponSendList?.couponVoList.filter(item => item.usableStatus === 1);
    },
    // 优惠券
    coupon() {
      // 原价 - 大促 - 优惠券
      const all = [];
      if (this.couponList && this.couponList.length) {
        all.push(...this.couponList);
      }
      if (this.couponVoList && this.couponVoList.length) {
        all.push(...this.couponVoList);
      }
      if (all.length) {
        return all.sort((a, b) => {
          return b.couponAmount - a.couponAmount;
        })[0];
      } else {
        return null;
      }
    },
    // 最终支付价
    payPrice() {
      // 原价 - 大促 - 优惠券，优先优惠券
      let price = this.$tools.formatNumber(this.pagePrice - this.promotionDiscountAmount);
      if (this.coupon) {
        // 原价 - 大促 - 优惠券
        const coupon = this.coupon;
        if (coupon.couponType === 2) {
          // 直减券
          price = this.$tools.formatNumber(price - coupon.couponAmount);
        } else if (price >= coupon.transactionAmount) {
          // 满减券
          price = this.$tools.formatNumber(price - coupon.couponAmount);
        }
      }
      if (price <= 0) {
        price = 0.01;
      }
      const arr = this.$tools.formatZero(price).split('.');
      const suffix = [];
      if (arr && arr.length === 2) {
        suffix.push(`.${arr[1]}`);
      }
      if ([2, 3].includes(this.skuMode)) {
        suffix.push('起');
      }
      return {
        value: price,
        prefix: arr[0],
        suffix: suffix.join('')
      };
    },
    adParams() {
      const { gdt_vid, qq_ac_id, qq_ag_id, clickid, adid, acode, callback, aid, cid, ksUnitId, ksSiteAccountId } = this.detail || {};
      return {
        gdt_vid,
        qq_ac_id,
        qq_ag_id,
        clickid,
        adid,
        acode,
        callback,
        aid,
        cid,
        ksUnitId,
        ksSiteAccountId
      };
    }
  },
  watch: {
    isActive(val) {
      this.isShowProduct = val;
    }
  },
  created() {
    this.isShowProduct = this.index === 0;
  },
  methods: {
    handleToDetail() {
      const { pageId, source, sourcePageId, isPrimaryPage, gdt_vid } = this.detail;
      const params = {
        pageId,
        source,
        gdt_vid,
        sourcePageId,
        ...this.adParams
      };
      if (isPrimaryPage) {
        params.isPrimaryPage = isPrimaryPage;
      }
      const query = this.$tools.object2param(params);
      uni.navigateTo({
        url: `/pages/advertising/index?${query}`
      });
    },
    // 优惠券领取成功回调
    handleSendCoupon() {
      this.isAlreadyReceive = true;
      const { pageId, productId, storeId, source } = this.detail || {};

      // 再次获取可使用的优惠券数据
      this.$store.dispatch('product/getCouponList', {
        storeId,
        productId,
        query: {
          pageId,
          source
        }
      }).then(() => {
        this.handleShowSku();
      }).catch((e) => {
        this.$XTrack('receive_coupon_fail', {
          page_id: pageId,
          product_id: productId,
          store_id: storeId,
          source,
          e: e
        });
        this.handleShowSku();
      });
    },

    handleCardSendCoupon() {
      this.isAlreadyReceive = true;
      this.handleToDetail();
    },
    // 显示订单表单
    handleShowSku() {
      this.$emit('confirm', this.detail);
    }
  }
};
</script>

<style lang="scss" scoped>
  .p-product{
    width: 100%; height: 100%; display: flex; align-items: flex-start; flex-direction: column;
    ._carousel{
      width: 100%; flex: 1; border-radius: 16px 16px 0 0; overflow: hidden; display: flex; flex-direction: column; position: relative; background-color: #000;
      ._picture{ width: 100%; position: relative; flex: 1; z-index: 1;}
      ._product{
        position: absolute; padding: 20px; width: 100%; bottom: 0; z-index: 2;
        &:before{ content: ''; position: absolute; left: 0; bottom: 0; width: 100%; height: 90%; background: linear-gradient(0deg, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0) 100%);}
        ._header{
          margin-bottom: 16px; display: flex; position: relative;
          ._abbreviation{
            display: flex; align-items: center; border-radius: 14px; background: rgba(27, 29, 31, 0.40); padding: 10px; color: #fff;
            ._tag{ margin-right: 10px; border-radius: 8px; background: linear-gradient(270deg, #5E6FF1 0%, #61A9F8 100%); font-size: 25px; padding: 2px 8px;}
            ._name{ font-size: 26px;}
          }
        }
        ._card{
          background-color: #fff; border-radius: 30px; padding: 18px; position: relative;
          ._price{
            display: flex; align-items: flex-end; line-height: 1; color: $uni-color-primary; font-weight: bold;
            ._new_name{ font-size: 30px; padding-bottom: 5px;}
            ._new_price{
              font-size: 56px; display: flex; align-items: flex-end;
              &:before{ content: '￥'; font-size: 30px; padding-bottom: 5px;}
              &:after{ content: attr(data-value); font-size: 30px; padding-bottom: 5px;}
            }
          }
          ._title{
            display: flex; align-items: center; padding: 10px 0;
            ._tag{ background-color: $uni-color-primary; color: #fff; padding: 2px 10px; font-size: 25px; margin-right: 6px; border-radius: 8px;}
            ._name{ flex: 1; font-size: 36px; font-weight: bold; color: #323233; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden; padding-right: 20px;}
            ._more{ color: $uni-color-primary; font-size: 32px; padding-left: 20px; line-height: 1; border-left: 2px solid #D9D9D9;}
          }

          .coupon-holder{
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
          }
        }
         ._animation{ opacity:0; animation: bounceInDown .5s forwards;}
      }
    }
    ._tools{
      width: 100%; padding: 20px; background: #000; text-align: right;
      ._button{ display: inline-block; border-radius: 50px; padding: 18px 40px; text-align: center; color: #fff; font-size: 32px; font-weight: bold; background: linear-gradient(90deg, #FF3728 0%, #FF8F27 100%);}
    }

    &.is-active{
      ._carousel{
        align-items: center;
      }
    }
  }

  @keyframes bounceInDown {
    0% {
      opacity: 0;
      transform: translate3d(0, 100%, 0)
    }
    to {
      opacity: 1;
      transform: translate3d(0, 0, 0)
    }
  }
</style>
